<template>
  <el-row style="height: 100vh; display: flex" :gutter="20">
    <el-col :span="5" id="left-tree" class="left-tree">
      <div class="comp-tree" style="padding: 10px; border-right: 1px solid #dfe6ec; display: block">
        <el-input placeholder="输入关键字进行过滤" v-model="filterText"> </el-input>

        <el-tree
          class="filter-tree"
          default-expand-all
          :filter-node-method="filterNode"
          ref="SlotTree"
          :default-expanded-keys="treeData"
          :current-node-key="currentNodekey"
          :data="treeList"
          :props="defaultProps"
          :expand-on-click-node="false"
          highlight-current
          :node-key="NODE_KEY"
          @node-click="handleNodeClick"
        >
          <template v-slot="{ node, data }">
            <el-tooltip :content="data.label" placement="top">
              <span>{{ data.label }}</span>
            </el-tooltip>
          </template>
        </el-tree>
        <!-- <div id="resize" class="resize" title="收缩侧边栏">
          <p>⋮</p>
        </div> -->
      </div>
      <!-- </div>
    </div> -->
    </el-col>
    <!-- <el-col :span="6">
      <div class="app-container calendar-list-container">
        <div id="treeBox" class="filter-container">
          <el-table :data="treeList" style="width: 100%;" row-key="id" border lazy :load="load"
            @row-click="getListByTreeId">
            <el-table-column prop="name" label="名称" sortable />
          </el-table>
        </div>
      </div>
    </el-col> -->
    <el-col id="right-content" class="right-content" :offset="0" :span="18">
      <div class="app-container">
        <div class="filter-container" v-if="!detailShow">
          <div class="filter-item">
            <span class="span">字段名称:</span>
            <el-input v-model="listQuery.columnName" placeholder="请输入字段名称" style="width: 200px" />
          </div>
          <div class="filter-item">
            <span class="span">字段注解:</span>
            <el-input v-model="listQuery.columnComment" placeholder="请输入字段注解" style="width: 200px" />
          </div>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
            {{ $t('table.search') }}
          </el-button>
          <!-- <el-button v-waves plain class="filter-item" style="margin-left: 10px" type="success" icon="el-icon-edit" @click="handleEdit">
            {{ $t('table.editentity') }}
          </el-button> -->
          <el-button v-waves plain class="filter-item" style="margin-left: 10px" type="primary" icon="el-icon-folder-opened" @click="handleSyncBtn">
            <!--            {{ $t('table.editentity') }}-->
            同步该表字段数据
          </el-button>
          <el-button v-waves plain class="filter-item" style="margin-left: 10px" type="success" icon="el-icon-male" @click="handleDetail"> 查看详情 </el-button>
          <el-button v-waves class="filter-item" icon="el-icon-refresh" @click="handleRest">{{ $t('table.rest') }}</el-button>
          <!--          <el-button v-waves v-permission="['metadata:column:add']" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">-->
          <!--            {{ $t('table.add') }}-->
          <!--          </el-button>-->
          <!--          <el-button v-waves v-permission="['metadata:column:delete']" class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="handleBathDelete">-->
          <!--            {{ $t('table.delete') }}-->
          <!--          </el-button>-->
          <!--          <el-button v-waves v-permission="['metadata:column:import']" class="filter-item" type="primary" icon="el-icon-upload2" @click="handleImport">-->
          <!--            {{ $t('table.import') }}-->
          <!--          </el-button>-->
          <!-- <el-button v-waves v-permission="['metadata:column:export']" :loading="downloadLoading" class="filter-item"
            type="primary" icon="el-icon-download" @click="handleExport">
            {{ $t('table.export') }}
          </el-button> -->
        </div>
        <div class="filter-container">
          <!-- <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
            @click="handleCreate">
            {{ $t('table.entity') }}
          </el-button> -->

          <!-- <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search"
            @click="handleCheck">
            {{ $t('table.checkentity') }}
          </el-button> -->
        </div>

        <el-table
          v-if="!detailShow"
          ref="table"
          :key="tableKey"
          v-loading="listLoading"
          element-loading-text="正在加载，请稍后"
          :data="list"
          border
          fit
          highlight-current-row
          max-height="600"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column align="center" type="index" width="50" label="序号">
            <template slot-scope="scope">
              <span>{{ (listQuery.page - 1) * listQuery.limit + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="拖拽" width="80">
            <template slot-scope="{}">
              <svg-icon class="drag-handler" icon-class="drag" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="表名称" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.tableName }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="表注释" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.tableComment.split('?')[0] }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="字段名称" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.columnName }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="字段注释" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.columnComment }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="是否主键" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.columnKey | dictLabel('sf') }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="是否为空" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.columnNullable | dictLabel('sf') }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="数据类型" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.dataType }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="数据长度" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.dataLength }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="数据精度" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.dataPrecision }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="标签" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.label }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="230" class-name="small-padding fixed-width" fixed="right">
            <template slot-scope="{ row }">
              <el-button v-if="row.labelId == null || row.labelId === ''" v-permission="['metadata:column:update']" type="text" size="small" icon="el-icon-connection" @click="handleUpdate(row)">
                标签绑定
              </el-button>
              <el-button v-if="row.labelId != null && row.labelId !== ''" v-permission="['metadata:column:update']" type="text" size="small" icon="el-icon-link" @click="handleUpdate1(row)">
                解除绑定
              </el-button>
              <!--              <el-button v-permission="['metadata:column:delete']" type="text" size="small" icon="el-icon-delete" class="delete-text-btn" @click="handleDelete(row)">-->
              <!--                {{ $t('table.delete') }}-->
              <!--              </el-button>-->
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0 && !detailShow" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" :page-sizes="pageArray" @pagination="getList" />
        <div v-if="detailShow">
          <div class="filter-container" style="margin-top: 10px">
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-back" @click="handleBack"> 返回 </el-button>
            <span style="margin-left: 20px">详细数据</span>
          </div>
          <el-table ref="table" :key="tableKey" element-loading-text="正在加载，请稍后" :data="arrlist" border fit highlight-current-row style="width: 100%" max-height="800px">
            <el-table-column v-for="(item, index) in headList" :key="index" :label="item" min-width="150px">
              <template slot-scope="{ row }">
                <span>{{ row[item] }}</span>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="arrtotal > 0" :total="arrtotal" :page.sync="listQuery1.pageNum" :limit.sync="listQuery1.pageSize" :page-sizes="pageArray" @pagination="handleDetail()" />
        </div>

        <import ref="import" template-url="/metadata/column/template" import-url="/metadata/column/import" @refreshList="getList" />
        <column-form ref="form" @refreshList="getList" />
        <entityForm ref="entityform" @refreshList="getList" />
        <entityList ref="entityList" />
      </div>
    </el-col>
  </el-row>
</template>

<style scoped>
/* 自定义节点的样式 */
.el-tree-node__content:hover {
  background-color: #e0e0e0;
  cursor: pointer;
}

/* 自定义工具提示的样式 */
.el-tooltip__popper {
  z-index: 9999;
  /* 确保工具提示显示在顶部 */
}
</style>

<script>
import { fetchsourceList } from '@/api/metadata/source'
import { deletecolumn, fetchcolumnList, exportcolumn, updatecolumn } from '@/api/metadata/column'
import Import from '@/components/Import/import'
import waves from '@/directive/waves' // waves directive
import permission from '@/directive/permission/permission'
import columnForm from './columnForm'
import entityForm from './entityForm.vue'
import entityList from './entityList.vue'
import Pagination from '@/components/Pagination'
import Sortable from 'sortablejs'
import { fetchMetadataLabelGroupList, syncColumn } from '@/api/metadata/label/metadataLabelGroup'
import { getDetail } from '@/api/masterdata/detailTable'
export default {
  name: 'columnList',
  components: { columnForm, Pagination, Import, entityForm, entityList },
  directives: { waves, permission },
  data() {
    return {
      detailShow: false, //是否展示详情
      listLoadingP: false,
      filterText: '',
      tableKey: 0,
      tableKey1: 0,
      treeList: [],
      labelList: [],
      list: null,
      total: 0,
      arrlist: null,
      multipleSelection: [],
      downloadLoading: false,
      listLoading: true,
      headList: null,
      pageArray: this.$store.getters.pageArray,
      arrtotal: '',
      listQuery1: {
        coreDataModel: 1,
        tableId: '',
        pageNum: 1,
        pageSize: this.$store.getters.defaultPageSize,
      },
      listQuery: {
        columnName: undefined,
        ancestralId: '3',
        page: 1,
        limit: this.$store.getters.defaultPageSize,
      },
      entityQuery: {},
      currentNodekey: '',
      treeData: [],
      defaultProps: {
        // 默认设置
        children: 'children',
        label: 'name',
      },
      NODE_KEY: 'id',
    }
  },
  computed: {
    ids() {
      const ids = []
      this.multipleSelection.forEach((ele) => {
        ids.push(ele.id)
      })
      return ids.join(',')
    },
  },
  created() {
    this.getTreeList()
    // this.getLabelList()
  },
  watch: {
    filterText(val) {
      this.$refs.SlotTree.filter(val)
    },
  },
  mounted() {
    this.dragControllerDiv()
  },
  methods: {
    handleDetail() {
      //点击查看详情
      this.detailShow = true
      this.listLoadingP = true
      getDetail(this.listQuery1).then((res) => {
        if (res.data.code == 200) {
          if (res.data.data !== '{}') {
            this.headList = res.data.data.columnNameList
            this.arrlist = res.data.data.pageResult.data
            this.arrtotal = res.data.data.pageResult.total
          }

          this.listLoadingP = false
          this.headList = res.data.data.columnNameList
          this.arrlist = res.data.data.pageResult.data
          this.arrtotal = res.data.data.pageResult.total
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    handleBack() {
      //从详情中返回
      this.detailShow = false
    },
    dragControllerDiv() {
      let left = document.getElementById('left-tree')
      let line = document.getElementById('resize')
      let right = document.getElementById('right-content')
      // 鼠标按下事件
      line.onmousedown = function (e) {
        let startX = e.clientX
        line.left = line.offsetLeft
        // 鼠标拖动事件
        document.onmousemove = function (e) {
          let moveLen = line.left + (e.clientX - startX)
          if (moveLen >= document.body.clientWidth * 0.1 && moveLen <= document.body.clientWidth * 0.4) {
            line.style.left = moveLen + 'px'
            left.style.width = moveLen + 'px'
            right.style.width = document.body.clientWidth - moveLen + 'px'
          }
        }
        document.onmouseup = function () {
          document.onmousemove = null
          document.onmouseup = null
        }
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },

    funindex(data) {
      var ids = []
      data.forEach((item) => {
        // 将当前对象的 id 添加到 ids 数组中
        ids.push(item.id)
        // 如果当前对象有 children 属性并且是一个数组，则递归调用 getAllIds 函数
        if (item.children && Array.isArray(item.children)) {
          // 递归调用 getAllIds 函数，将结果合并到 ids 数组中
          ids = ids.concat(this.funindex(item.children))
        }
      })
      return ids
    },
    handleNodeClick(data) {
      this.detailShow = false //每次切换模块时让详情撤回来
      this.listQuery.sourceId = data.id
      this.listQuery1.tableId = data.id
      this.getList()
      // this.handleClick()
    },
    getTreeList() {
      this.listLoading = true
      fetchsourceList(this.listQuery).then((response) => {
        if (response.data.code === 0) {
          this.treeList = response.data.data
          this.handlefun(this.treeList)
          if (this.treeList.length > 0) {
            this.currentNodekey = this.treeList[0].id
            this.handleNodeClick(this.treeList[0])
            this.$nextTick(() => {
              this.$refs.SlotTree.setCurrentKey(this.currentNodekey) //一定要加这个选中了否则样式没有出来
            })
          }
          this.listLoading = false
        } else {
          this.$message.error(response.data.msg)
        }
        this.listLoading = false
      })
    },
    getLabelList() {
      this.listLoading = true
      fetchMetadataLabelGroupList(this.listQuery).then((response) => {
        if (response.data.code === 0) {
          this.labelList = response.data.data
          this.listLoading = false
          this.$refs.form.setList(this.labelList)
        } else {
          this.$message.error(response.data.msg)
        }
        this.listLoading = false
      })
    },
    //编辑实体按钮
    handleEdit() {
      if (this.listQuery.sourceId) {
        this.entityQuery.tableId = this.listQuery.sourceId
        this.$refs.entityform.handleUpdate()
        this.$refs.entityform.setList(this.entityQuery)
      } else {
        this.$message.warning('请先选择表')
      }
    },

    handleSyncBtn() {
      if (this.listQuery.sourceId) {
        syncColumn(this.listQuery.sourceId).then((response) => {
          if (response.data.code === 0) {
            this.$message.success('数据同步成功')
          } else {
            this.$message.error('数据同步失败')
          }
        })
      } else {
        this.$message.warning('请先选择表')
      }
    },

    //定义实体按钮
    handleCreate() {
      if (this.listQuery.sourceId) {
        this.entityQuery.tableId = this.listQuery.sourceId
        this.$refs.entityform.setList(this.entityQuery)
        this.$refs.entityform.handleCreate()
      } else {
        this.$message.warning('请先选择表')
      }
      // this.$refs.entityform.setList(this.labelList)
    },
    //查看实体按钮
    handleCheck() {
      if (this.listQuery.sourceId) {
        this.entityQuery.tableId = this.listQuery.sourceId
        this.$refs.entityList.setList(this.entityQuery)
        this.$refs.entityList.handleCheck()
      } else {
        this.$message.warning('请先选择表')
      }
    },
    load(tree, treeNode, resolve) {
      resolve(tree.children)
    },
    getList() {
      if (!this.listQuery.sourceId) {
        this.$message.error('请选择一个数据表')
        return
      }

      this.listLoading = true
      fetchcolumnList(this.listQuery).then((response) => {
        if (response.data.code == 0) {
          if (response.data.data.length) {
            this.listLoading = false
            this.list = response.data.data
            this.total = response.data.total
            this.setSort()
          }
          this.getList1()
        }
      })
    },
    handleUpdate(row) {
      this.$refs.form.handleUpdate(row.id)
    },
    handlefun(item) {
      item.map((v, i) => {
        if (v.children && v.children.length) {
          this.handlefun(v.children)
        }
        v.label = v.label.split('?')[0]
      })
      return item
    },
    handleUpdate1(row) {
      this.$confirm('确定解除标签绑定吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const data = row
        data.labelId = ''
        updatecolumn(data).then((response) => {
          this.loading = false
          if (response.data.code === 0) {
            this.dialogFormVisible = false
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleDelete(row) {
      this.$confirm('确定删除该数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deletecolumn(row.id).then((response) => {
          if (response.data.code === 0) {
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleBathDelete() {
      if (this.ids === '') {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定删除所选数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deletecolumn(this.ids).then((response) => {
          if (response.data.code === 0) {
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleImport() {
      this.$refs.import.show()
    },
    handleExport() {
      if (this.ids === '') {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.downloadLoading = true
      exportcolumn(this.ids).then((response) => {
        this.downloadLoading = true
        if (response.data.code === 0) {
          import('@/vendor/Export2Excel').then((excel) => {
            excel.export_byte_to_excel(response.data.data.bytes, response.data.data.title)
            this.downloadLoading = false
          })
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    setSort() {
      const el = this.$refs.table.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        setData: function (dataTransfer) {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: (evt) => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)
          // TODO：这里完成自己的业务处理
        },
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    //重置
    handleRest() {
      this.listQuery = {
        sourceId: this.listQuery.sourceId,
        page: this.listQuery.page,
        limit: this.$store.getters.defaultPageSize,
      }
      this.getList()
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep(::-webkit-scrollbar) {
  display: block !important;
}

::v-deep(.el-table) {
  overflow: none !important;
}

#treeBox {
  margin-top: 1px;

  .el-table thead {
    display: none;
  }
}

.span {
  color: #606266;
  font-weight: 700;
  font-size: 14px;
}

.left-tree {
  position: relative;
  width: 331.83px !important;
  height: 1080px !important;
  background: #fff;
  // box-shadow: 0 0 2px 2px rgba(0, 0, 0, 0.050980392156862744);
  border-radius: 4px;
  vertical-align: top;
  display: inline-block;
  box-sizing: border-box;
  -ms-flex-negative: 0;
  flex-shrink: 0;
  padding: 10px 0 0 10px;
  // margin-right: 8px;
}

.resize {
  cursor: col-resize;
  position: absolute;
  top: 45%;
  right: -8px;
  background-color: #d6d6d6;
  border-radius: 5px;
  margin-top: -10px;
  width: 10px;
  height: 50px;
  background-size: cover;
  background-position: 50%;
  font-size: 32px;
  color: #fff;
  display: flex;
  /* 使用 flex 布局 */
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 垂直居中 */
}

.right-content {
  display: inline-block;
  height: 100%;
  background: #fff;
  -webkit-box-shadow: 0 0 2px 2px rgba(0, 0, 0, 0.050980392156862744);
  box-shadow: 0 0 2px 2px rgba(0, 0, 0, 0.050980392156862744);
  border-radius: 4px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  padding: 10px;
  vertical-align: top;
  overflow: auto;
}

.el-row {
  display: flex;
}

.el-col-5 {
  flex: 1;
}
</style>
